<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="70px"
    >
      <el-row>
        <el-form-item label="客户" prop="customerId">
          <el-select
            v-model="queryParams.customerId"
            clearable
            filterable
            placeholder="请选择客户"
            class="!w-200px"
          >
            <el-option
              v-for="item in customerList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <!--        <el-form-item label="审批状态" prop="status">-->
        <!--          <el-select-->
        <!--            v-model="queryParams.status"-->
        <!--            clearable-->
        <!--            filterable-->
        <!--            placeholder="请选择状态"-->
        <!--            class="!w-120px"-->
        <!--          >-->
        <!--            <el-option-->
        <!--              v-for="item in statusList"-->
        <!--              :key="item.value"-->
        <!--              :label="item.label"-->
        <!--              :value="item.value"-->
        <!--            />-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->

        <el-form-item label="车牌号" prop="licensePlate">
          <el-input v-model="queryParams.licensePlate" clearable style="width: 200px" placeholder="请输入车牌号"/>
        </el-form-item>
        <el-form-item label="车型" prop="typeCar">
          <el-input v-model="queryParams.typeCar" style="width: 200px" placeholder="请输入车型"/>
        </el-form-item>
        <!--        <el-form-item label="销售日期" prop="orderTime">-->
        <!--          <el-date-picker-->
        <!--            v-model="queryParams.orderTime"-->
        <!--            value-format="YYYY-MM-DD HH:mm:ss"-->
        <!--            type="daterange"-->
        <!--            start-placeholder="开始日期"-->
        <!--            end-placeholder="结束日期"-->
        <!--            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"-->
        <!--            class="!w-220px"-->
        <!--          />-->
        <!--        </el-form-item>-->
        <el-form-item label="完工日期" prop="orderTime">
          <el-date-picker
            v-model="queryParams.completeDate"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            class="!w-220px"
          />
        </el-form-item>
		<el-form-item label="产品名称" prop="productId">
		  <el-select
		    v-model="queryParams.productId"
		    clearable
		    filterable
		    placeholder="请选择产品名称"
		    class="!w-200px"
		  >
		    <el-option
		      v-for="item in productList"
		      :key="item.id"
		      :label="item.name"
		      :value="item.id"
		    />
		  </el-select>
		</el-form-item>

          <el-button @click="handleQuery">
            <Icon icon="ep:search" class="mr-5px"/>
            搜索
          </el-button>

          <el-button @click="resetQuery">
            <Icon icon="ep:refresh" class="mr-5px"/>
            重置
          </el-button>
		  <el-button
		    type="primary"
		    plain
		    @click="openForm('create')"
		    v-hasPermi="['erp:sale-order:create']"
		  >
		    <Icon icon="ep:plus" class="mr-5px"/>
		    新增
		  </el-button>
		  <!-- v-hasPermi="['erp:sale:export']" -->
		  <el-button type="success" plain @click="handleExport">
		    <Icon icon="ep:download" class="mr-5px" /> 导出
		  </el-button>
		  <!-- v-hasPermi="['erp:sale:import']" -->
		  <el-button type="warning" plain @click="handleImport">
		    <Icon icon="ep:upload" /> 导入
		  </el-button>

      </el-row>
      <el-row :gutter="10" style="margin-top: 5px">
        <el-col :span="4">
          <!--          <span style="font-size: 12px">完工状态:</span>-->
          <el-radio-group v-model="completeRadio" size="small">
            <el-radio-button @click="handleCompleteQuery(undefined)" label="所有" value="0"/>
            <el-radio-button @click="handleCompleteQuery(1)" label="未完工" value="1"/>
            <el-radio-button @click="handleCompleteQuery(2)" label="已完工" value="2"/>
          </el-radio-group>
        </el-col>

        <el-col :span="4">
          <el-radio-group v-model="auditStatusRadio" size="small">
            <el-radio-button @click="handleAuditStatusQuery(undefined)" label="所有" value="1"/>
            <el-radio-button @click="handleAuditStatusQuery(10)" label="未审批" value="10"/>
            <el-radio-button @click="handleAuditStatusQuery(20)" label="已审批" value="20"/>
          </el-radio-group>
        </el-col>

        <el-col :span="6">
          <el-radio-group v-model="purchaseRadio" size="small">
            <el-radio-button @click="handlePurchaseQuery(undefined)" label="所有" value="0"/>
            <el-radio-button @click="handlePurchaseQuery(1)" label="未采购" value="1"/>
            <el-radio-button @click="handlePurchaseQuery(2)" label="采购中" value="2"/>
            <el-radio-button @click="handlePurchaseQuery(3)" label="已采购" value="3"/>
          </el-radio-group>
        </el-col>
		
		<el-col :span="4"> 
		  <el-radio-group v-model="payRadio" size="small">
		    <el-radio-button @click="handlePayQuery(undefined)" label="所有" value="0"/>
			<el-radio-button @click="handlePayQuery(1)" label="已付款" value="1"/>
			<el-radio-button @click="handlePayQuery(2)" label="未付款" value="2"/>
		  </el-radio-group>
		</el-col>
		
		<el-col :span="4">
		  <el-radio-group v-model="getPayRadio" size="small">
		    <el-radio-button @click="handleGetPayQuery(undefined)" label="所有" value="0"/>
			<el-radio-button @click="handleGetPayQuery(1)" label="已收款" value="1"/>
			<el-radio-button @click="handleGetPayQuery(2)" label="未收款" value="2"/>
		  </el-radio-group>
		</el-col>
		
      </el-row>


    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>

    <!--    <el-row :gutter="20">-->
    <!--      <el-col :span="1" :offset="23">-->
    <!--        <el-switch-->
    <!--          v-model="showLeftData"-->
    <!--          width="48px"-->
    <!--          class="is-rect"-->
    <!--          size="large"-->
    <!--        />-->
    <!--      </el-col>-->
    <!--    </el-row>-->

    <el-table
      border
      v-loading="loading"
      :summary-method="getSummaries" show-summary
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleSelectionChange"
    >

      <el-table-column fixed="left" label="操作" width="60" align="center">
        <template #default="scope"> <!-- :visible="popoverVisible == scope.row.id" -->  
          <el-popover style="position: relative" 
                      placement="bottom-start"
                      :width="60">

            <el-row class="mb-8px">
              <el-col :span="24">
                <el-button
                  link
                  @click="openForm('detail', scope.row.id)"
                  v-hasPermi="['erp:sale-order:query']"
                >
                  详情
                </el-button>
              </el-col>
            </el-row>

            <span v-if="scope.row.completeStatus !=4">
<!--            <el-row class="mb-8px">-->
              <!--              <el-col :span="24">-->
              <!--                <el-button-->
              <!--                  link-->
              <!--                  type="primary"-->
              <!--                  @click="openForm('update', scope.row.id)"-->
              <!--                  v-hasPermi="['erp:sale-order:update']"-->
              <!--                  :disabled="scope.row.status === 20"-->
              <!--                >-->
              <!--                  编辑-->
              <!--                </el-button>-->
              <!--              </el-col>-->
              <!--            </el-row>-->


              <!--            <el-row class="mb-8px" v-if="scope.row.status === 10">-->
              <!--              <el-col :span="24">-->
              <!--                <el-button-->
              <!--                  link-->
              <!--                  type="primary"-->
              <!--                  @click="handleUpdateStatus(scope.row.id, 20)"-->
              <!--                  v-hasPermi="['erp:sale-order:update-status']"-->
              <!--                >-->
              <!--                  审批-->
              <!--                </el-button>-->
              <!--              </el-col>-->
              <!--            </el-row>-->


              <!--            <el-row class="mb-8px" v-else>-->
              <!--              <el-col :span="24">-->
              <!--                <el-button-->
              <!--                  link-->
              <!--                  type="danger"-->
              <!--                  @click="handleUpdateStatus(scope.row.id, 10)"-->
              <!--                  v-hasPermi="['erp:sale-order:update-status']"-->
              <!--                >-->
              <!--                  反审-->
              <!--                </el-button>-->
              <!--              </el-col>-->
              <!--            </el-row>-->


            <el-row class="mb-8px">
              <el-col :span="24">
                <el-button
                  link
                  type="danger"
                  @click="handleDelete([scope.row.id])"
                  v-hasPermi="['erp:sale-order:delete']"
                >
                  删除
                </el-button>
              </el-col>
            </el-row>



            <el-row class="mb-8px">
              <el-col :span="24">
                <el-button
                  link
                  type="parimary"
                  @click="handleCreatePurchaseOrder(scope.row.id)"
                  v-hasPermi="['erp:sale-order:delete']"
                  v-if="scope.row.status === 10"
                >
                  提交采购
                </el-button>
              </el-col>
            </el-row>


            <el-row class="mb-8px">
              <el-col :span="24">
                <el-button
                  link
                  type="parimary"
                  @click="handleQueryPurchaseOrder(scope.row.id)"
                  v-hasPermi="['erp:sale-order:delete']"
                >
                  查看采购
                </el-button>
              </el-col>
            </el-row>

              <el-row class="mb-8px">
              <el-col :span="24">
                <el-button
                  link
                  type="parimary"
                  @click="handleQueryPurchaseIn(scope.row.id)"
                  v-hasPermi="['erp:sale-order:delete']"
                >
                  查看入库
                </el-button>
              </el-col>
            </el-row>

            <el-row class="mb-8px">
            <el-col :span="24">
              <el-button
                link
                type="parimary"
                @click="handleQueryPay(scope.row.id)"
                v-hasPermi="['erp:sale-order:delete']"
              >
                查看付款
              </el-button>
            </el-col>
          </el-row>


              <el-row class="mb-8px">
            <el-col :span="24">
              <el-button
                link
                type="parimary"
                @click="handleQuerySaleOut(scope.row.id)"
                v-hasPermi="['erp:sale-order:delete']"
              >
                销售出库
              </el-button>
            </el-col>
          </el-row>


               <el-row class="mb-8px">
            <el-col :span="24">
              <el-button
                link
                type="parimary"
                @click="handleQueryReceipt(scope.row.id)"
                v-hasPermi="['erp:sale-order:delete']"
              >
                查看收款
              </el-button>
            </el-col>
          </el-row>


            <el-row class="mb-8px">
              <el-col :span="24">

                <el-button
                  link
                  type="parimary"
                  @click="handleSendOrder(scope.row.id)"
                  v-hasPermi="['erp:sale-order:delete']"
                >
                  发单
                </el-button>
              </el-col>
            </el-row>
            </span>

            <div class="popoverCloseBtn" @click="closePopover()">关闭</div>

            <!--            <img style="text-align: right;width: 32px;" src="@/assets/imgs/close.png"-->
            <!--                 @click="closePopover()"/>-->
            <template #reference>
              <img src="@/assets/imgs/more_edit.png" ref="targetTool" class="linkBtn"
                   @contextmenu.prevent="handleRightClick(scope.row.id)"
                   @click="openForm('update', scope.row.id)"/>
            </template>
            <!--            @dblclick="openForm('update', scope.row.id)"-->
          </el-popover>
        </template>
      </el-table-column>

      <!--      <el-table-column width="30" label="选择" type="selection"/>-->
      <!--      <el-table-column min-width="180" label="销售订单号" align="center" prop="no"/>-->
      <el-table-column label="审批" fixed="left" align="center" prop="status" min-width="90">
        <template #default="scope">
          <el-tag @click="handleUpdateStatus(scope.row.id, 10)" class="statusTag" type="success"
                  v-if="scope.row.status == 20">已审
          </el-tag>
          <el-tag @click="handleUpdateStatus(scope.row.id, 20)" class="statusTag" type="warning"
                  v-else>未审
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="采购" fixed="left" align="center" prop="purchaseStatus"
                       min-width="90">
        <template #default="scope">
          <el-button v-if="scope.row.purchaseStatus == 1"
                     @click="handleCreatePurchaseOrder(scope.row.id)" link type="danger">待采购
          </el-button>
          <el-button v-else-if="scope.row.purchaseStatus == 2"
                     @click="handleQueryPurchaseOrder(scope.row.id)" link type="warning">采购中
          </el-button>
          <el-button v-else-if="scope.row.purchaseStatus == 3"
                     @click="handleQueryPurchaseOrder(scope.row.id)" link type="success">已采购
          </el-button>
        </template>
      </el-table-column>


      <el-table-column
        label="订单时间"
        fixed="left"
        prop="orderTime"
        :formatter="dateFormatter2"
        width="110px"
      />


      <el-table-column label="客户" fixed="left" prop="customerName" min-width="100"/>
      <el-table-column label="车牌号" fixed="left" prop="licensePlate" min-width="100"/>
      <!--      <el-table-column label="车型/服务" fixed="left" prop="typeCar" min-width="120"/>-->

      <!--      <el-table-column label="注释" fixed="left" prop="annotationTxt" min-width="120"/>-->

      <el-table-column label="产品名称" fixed="left" prop="productNames" min-width="200">
        <template #default="scope">

          <div
            v-for="(item, index) in scope.row.items"
            :key="index"
            @click="handleProductClick(item)"
            style="margin-right: 5px;display: block;vertical-align: middle;line-height: 20px;margin-bottom: 10px;cursor: pointer"
          >
            <span v-if="item.brandName != null && item.brandName.length>0">
              【{{ item.brandName }}】
            </span>
            {{ item.productName }}
            <span v-if="item.businessTypeName != null && item.businessTypeName.length>0">
              {{ item.businessTypeName }}
            </span>
            <!--            【{{ item.brandName }}】{{ item.productName }}{{ item.businessTypeName }}-->
          </div>
        </template>
      </el-table-column>
      <el-table-column label="备注" fixed="left" prop="remark" min-width="120">
        <template #default="scope">
          <el-input class="no-border-input"  @change="handleRemarkChange(scope.row)" v-model="scope.row.remark" type="text" :rows="2"/>
<!--          <div @click="handleRemarkClick(scope.row)" style="cursor: pointer">-->
<!--            {{ scope.row.remark }}-->
<!--          </div>-->
        </template>
      </el-table-column>
      <el-table-column label="VIN" fixed="left" prop="vin" min-width="100"/>
      <el-table-column label="销售价格" align="center" prop="sumSalePrice" min-width="130">
        <template #default="scope">
          {{ computeAllPrice(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column label="进价" align="center" prop="sumPurchasePrice" min-width="130">
        <template #default="scope">
          <!--          v-if="getPurchasePrice(scope.row)>0"-->
          <el-tag @click="handleUpdatePurchasePrice(scope.row)"
                  class="statusTag">{{ getPurchasePrice(scope.row) }}
          </el-tag>
          <!--          <span v-else>{{ getPurchasePrice(scope.row) }}</span>-->
        </template>
      </el-table-column>

      <el-table-column
        label="技师提成"
        align="center"
        prop="sumEngineerCost"
        min-width="100"
      >
        <template #default="scope">
          <el-tag @click="handleUpdateEngineerCost(scope.row)"
                  class="statusTag">{{ getEngineerCost(scope.row.engineerList) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="完工状态" align="center" prop="completeStatus" min-width="120">
        <template #default="scope">
          <div
            :class="['custom-select', { 'priorit1': scope.row.completeStatus === 1, 'priorit2': scope.row.completeStatus === 2 }]">
            <el-select style="text-align: center;"
                       @change="handleCompleteStatusChange(scope.row)"
                       v-model="scope.row.completeStatus">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.ERP_COMPLETE_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </div>
        </template>
      </el-table-column>


      <el-table-column
        label="完工时间"
        align="center"
        prop="completeDate"
        :formatter="dateFormatter2"
        width="120px"
      >
        <template #default="scope">
          <el-button
            type="text"
            @click="handleCompleteDateClick(scope.row)"
          >
            {{ formatDate(scope.row.completeDate, 'YYYY-MM-DD') }}
          </el-button>
        </template>
      </el-table-column>

      <el-table-column
        label="订金"
        align="center"
        prop="depositPrice"
        :formatter="erpPriceTableColumnFormatter"
        min-width="100"
      />


      <el-table-column
        label="外协费用"
        align="center"
        prop="sumOutsourceCost"
        min-width="100"
      >
        <template #default="scope">
          {{ getOutsourceCost(scope.row.outsourceList) }}
        </template>
      </el-table-column>

      <el-table-column
        label="销售提成"
        align="center"
        min-width="100"
        prop="sumSaleCost"
      >
        <template #default="scope">
          {{ scope.row.saleUserCost == null ? 0 : scope.row.saleUserCost }}
        </template>
      </el-table-column>
      <el-table-column
        label="渠道提成"
        align="center"
        min-width="100"
        prop="sumChannelCost"
      >
        <template #default="scope">
          {{ scope.row.channelCost == null ? 0 : scope.row.channelCost }}
        </template>
      </el-table-column>

      <el-table-column
        label="其他费用"
        align="center"
        min-width="100"
        prop="sumOtherCost"
      >
        <template #default="scope">
          {{ getOtherCost(scope.row.otherCostList) }}
        </template>
      </el-table-column>

      <el-table-column
        label="毛利"
        align="center"
        min-width="80"
        prop="sumGrossProfit"
        :formatter="erpPriceTableColumnFormatter"
      >
        <template #default="scope">
          {{ getGrossProfit(scope.row) }}
        </template>

      </el-table-column>

      <el-table-column label="创建人" align="center" prop="creatorName"/>
      <el-table-column label="创建时间" :formatter="dateFormatter" min-width="200" align="center"
                       prop="createTime"/>

      <el-table-column label="状态" v-if="showLeftData" align="center" fixed="right" width="90"
                       prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.ERP_AUDIT_STATUS" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <!--      <el-table-column v-if="showLeftData" label="操作" align="center" fixed="right" width="200">-->
      <!--        <template #default="scope">-->
      <!--          <el-button-->
      <!--            link-->
      <!--            @click="openForm('detail', scope.row.id)"-->
      <!--            v-hasPermi="['erp:sale-order:query']"-->
      <!--          >-->
      <!--            详情-->
      <!--          </el-button>-->
      <!--          <span v-if="scope.row.completeStatus !=4">-->
      <!--          <el-button-->
      <!--            link-->
      <!--            type="primary"-->
      <!--            @click="openForm('update', scope.row.id)"-->
      <!--            v-hasPermi="['erp:sale-order:update']"-->
      <!--            :disabled="scope.row.status === 20"-->
      <!--          >-->
      <!--            编辑-->
      <!--          </el-button>-->
      <!--          <el-button-->
      <!--            link-->
      <!--            type="primary"-->
      <!--            @click="handleUpdateStatus(scope.row.id, 20)"-->
      <!--            v-hasPermi="['erp:sale-order:update-status']"-->
      <!--            v-if="scope.row.status === 10"-->
      <!--          >-->
      <!--            审批-->
      <!--          </el-button>-->
      <!--          <el-button-->
      <!--            link-->
      <!--            type="danger"-->
      <!--            @click="handleUpdateStatus(scope.row.id, 10)"-->
      <!--            v-hasPermi="['erp:sale-order:update-status']"-->
      <!--            v-else-->
      <!--          >-->
      <!--            反审-->
      <!--          </el-button>-->
      <!--          <el-button-->
      <!--            link-->
      <!--            type="danger"-->
      <!--            @click="handleDelete([scope.row.id])"-->
      <!--            v-hasPermi="['erp:sale-order:delete']"-->
      <!--          >-->
      <!--            删除-->
      <!--          </el-button>-->

      <!--          <el-button-->
      <!--            link-->
      <!--            type="parimary"-->
      <!--            @click="handleCreatePurchaseOrder(scope.row.id)"-->
      <!--            v-hasPermi="['erp:sale-order:delete']"-->
      <!--            v-if="scope.row.status === 10"-->
      <!--          >-->
      <!--            采购-->
      <!--          </el-button>-->

      <!--          <el-button-->
      <!--            link-->
      <!--            type="parimary"-->
      <!--            @click="handleSendOrder(scope.row.id)"-->
      <!--            v-hasPermi="['erp:sale-order:delete']"-->
      <!--            v-if="scope.row.status === 20"-->
      <!--          >-->
      <!--            发单-->
      <!--          </el-button>-->
      <!--          </span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>


  <el-dialog
    v-model="dialogInventoryVisible"
    title="发单信息"
    width="80%"
  >
    <div ref="contentToConvert">
      <el-container>
        <el-header
          style="background-color: darkgray;text-align: center;font-size: 36px;font-weight: 900">
          成都鑫易隆汽车用品有限公司
        </el-header>
        <el-divider content-position="center">
          <span style="font-size: 20px">销售清单</span>
        </el-divider>
        <el-row :gutter="20" style="font-size: 18px">
          <el-col :span="6">
            <div style="text-align: left;margin-left: 20px">客户名称：{{ printData.customerName }}
            </div>
          </el-col>
          <el-col :span="6">
            <div style="text-align: left;margin-left: 20px">车牌：{{ printData.carNumber }}
            </div>
          </el-col>
          <el-col :span="6">
            <div style="text-align: center">公司电话：028-65480298</div>
          </el-col>
          <el-col :span="6">
            <div style="text-align: right;margin-right: 20px">单号：{{ printData.no }}</div>
          </el-col>
        </el-row>
        <el-main>
          <el-table style="font-size: 18px;" border :data="printData.items">
            <el-table-column label="产品名称" min-width="300" align="center" prop="productName"/>
            <!--            <el-table-column label="品牌" align="center" prop="brandName"/>-->
            <el-table-column label="单价" align="center" prop="productPrice"/>
            <el-table-column label="数量" align="center" prop="count"/>
            <el-table-column label="小计" align="center" prop="subtotal"/>
            <!--          <el-table-column label="备注" align="center" prop="remark"/>-->
          </el-table>
        </el-main>
        <el-row :gutter="20" style="font-size: 16px;margin-bottom: 20px">
          <el-col :span="4">
            <div style="text-align: left;margin-left: 20px">打印人员：{{ printData.creatorName }}
            </div>
          </el-col>
          <el-col :span="6">
            <div style="text-align: left">完工时间：{{ formatDate(printData.completeTime) }}</div>
          </el-col>
          <el-col :span="14">
            <div style="text-align: right;margin-right: 20px;color: orangered;font-weight: 800">
              合计：￥{{ printData.allPrice }}
            </div>
          </el-col>
        </el-row>
        <el-row style="font-size: 16px;margin-bottom: 20px">
          <el-col :span="24">
            <div style="text-align: left;margin-left: 20px">备注信息：{{ printData.remark }}</div>
          </el-col>
        </el-row>
      </el-container>

    </div>
    <div style="text-align: center">
      <el-button type="primary" style="text-align: center" @click="generateImage">下载单据信息
      </el-button>
    </div>


  </el-dialog>

  <!-- 表单弹窗：添加/修改 -->
  <SaleOrderForm ref="formRef" @success="getList"/>

  <!--同步产品编号和名称-->
  <el-dialog
    v-model="dialogProductVisible"
    title="同步产品信息"
    width="500"
  >
    <el-form label-width="100px">
      <el-form-item label="工厂名称">
        <el-input placeholder="请输入名称" v-model="syncProductInfoData.name"/>
      </el-form-item>
      <el-form-item label="工厂编号">
        <el-input placeholder="请输入编号" v-model="syncProductInfoData.factoryNumber"/>
      </el-form-item>

      <el-form-item label="VIN">
        <el-input placeholder="请输入VIN" v-model="syncProductInfoData.vin"/>
      </el-form-item>

      <el-form-item label="OE">
        <el-input placeholder="请输入OE" v-model="syncProductInfoData.oe"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogProductVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSyncProductInfo">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!--  修改完工日期-->
  <el-dialog
    v-model="dialogCompleteDateVisible"
    title="修改完工日期"
    width="20%"
  >
    <!--    <span class="demonstration">完工日期</span>-->
    <el-date-picker
      v-model="completeDateData.completeDate"
      type="date"
      placeholder="请选择日期"
    />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogCompleteDateVisible = false">取消</el-button>
        <el-button type="primary" @click="dealCompleteDate"
        >确定</el-button
        >
      </span>
    </template>
  </el-dialog>

  <!--  修改备注-->
  <el-dialog
    v-model="dialogRemarkVisible"
    title="修改备注"
    width="20%"
  >
    <el-input v-model="updateRemarkData.remark"/>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogRemarkVisible = false">取消</el-button>
        <el-button type="primary" @click="dealUpdateRemark"
        >确定</el-button
        >
      </span>
    </template>
  </el-dialog>

  <el-dialog
    v-model="dialogPurchaseVisible"
    title="调整采购价"
    width="40%"
  >
    <el-table border :data="purchaseInfo">
      <el-table-column label="产品名称" align="center" prop="productVo.name"/>
      <el-table-column label="采购价" align="center" width="100">
        <template #default="scope">
          <el-input
            v-model="scope.row.purchasePrice"
            placeholder="请输入采购价"
            @input="scope.row.purchasePrice = erpPriceInputFormatter(scope.row.purchasePrice)"
          />
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogPurchaseVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSyncPurchasePrice"
        >确定</el-button
        >
      </span>
    </template>
  </el-dialog>


  <el-dialog
    v-model="dialogEngineerVisible"
    title="修改技师提成"
    width="40%"
  >
    <el-table :data="formEngineerData" border class="-mt-10px">
      <el-table-column label="技师姓名" align="center" min-width="120">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.id`" class="mb-0px!">
            <el-select
              v-model="row.id"
              clearable
              filterable
              placeholder="请选择技师"
            >
              <el-option
                v-for="item in engineerList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="提成金额" prop="cost" align="center" min-width="120">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.cost`" class="mb-0px!">
            <el-input-number
              v-model="row.cost"
              controls-position="right"
              :min="0"
              :precision="0"
              class="!w-100%"
            />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.remark`" class="mb-0px!">
            <el-input v-model="row.remark" placeholder="请输入备注"/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ $index }">
          <el-button @click="handleEngineerDelete($index)" link>—</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-row justify="center" class="mt-3">
      <el-button @click="handleEngineerAdd" round>+ 添加技师</el-button>
    </el-row>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogEngineerVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSyncEngineerList">确定</el-button>
      </span>
    </template>
  </el-dialog>
  
  <!-- 用户导入对话框 -->
  <ImportForm ref="importFormRef" @success="getList" />
  
</template>

<script setup lang="ts">
import {DICT_TYPE, getIntDictOptions} from '@/utils/dict'
import {dateFormatter2, dateFormatter, formatDate} from '@/utils/formatTime'
import download from '@/utils/download'
import {SaleOrderApi, SaleOrderVO} from '@/api/erp/sale/order'
import SaleOrderForm from './SaleOrderForm.vue'
import {ProductApi, ProductVO} from '@/api/erp/product/product'
import {UserVO} from '@/api/system/user'
import * as UserApi from '@/api/system/user'
import {
  erpCountTableColumnFormatter,
  erpPriceInputFormatter,
  erpPriceTableColumnFormatter
} from '@/utils'
import {CustomerApi, CustomerVO} from '@/api/erp/sale/customer'
import {ElLoading, ElMessage, ElMessageBox} from 'element-plus'
import {onBeforeRouteUpdate} from 'vue-router';
import {SaleOutApi, SaleOutVO} from '@/api/erp/sale/out'
import ContentWrap from "@/components/ContentWrap/src/ContentWrap.vue";

import ImportForm from './ImportForm.vue'

const engineerList = ref<EngineerVO[]>([])
const formEngineerData = ref([])
/**
 * 打印账单
 */
import html2canvas from 'html2canvas';
import {string} from "vue-types";
import {EngineerApi, EngineerVO} from "@/api/erp/engineer";

const contentToConvert = ref(null);
const printData = ref({
  creatorName: '',
  completeTime: '',
  allPrice: '',
  carNumber: '',
  customerName: '',
  no: '',
  items: []
});



const handleRemarkChange = async (row) => {
  updateRemarkData.id = row.id;
  updateRemarkData.remark = row.remark;
  //确认是否修改
  await message.confirm('是否修改备注？');

  //修改中
  const loading = ElLoading.service({
    lock: true,
    text: '修改中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  try {
    SaleOrderApi.updateRemark(updateRemarkData).then(() => {
      ElMessage.success('修改成功')
      getList()
    })
  } finally {
    loading.close();}
};

const handleRemarkClick = (row: any) => {
  updateRemarkData.id = row.id;
  updateRemarkData.remark = row.remark;
  dialogRemarkVisible.value = true;
};
const dealUpdateRemark = () => {

  //修改中
  const loading = ElLoading.service({
    lock: true,
    text: '修改中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  try {
    SaleOrderApi.updateRemark(updateRemarkData).then(() => {
      ElMessage.success('修改成功')
      getList()
    })
  } finally {
    loading.close();
    dialogRemarkVisible.value = false;
  }


};

const popoverVisible = ref(null);

const generateImage = async () => {
  try {
    const loading = ElLoading.service({
      lock: true,
      text: '下载中...',
      background: 'rgba(0, 0, 0, 0.7)',
    })
    const canvas = await html2canvas(contentToConvert.value);
    const base64Img = canvas.toDataURL('image/png');
    downloadImage(base64Img, 'image.png');
    loading.close();
    ElMessage.success('下载成功');
  } catch (error) {
    console.error('生成时发生错误:', error);
  }
};
// 下载图片的辅助函数
const downloadImage = (base64Data, filename) => {
  // 创建隐藏的可下载链接
  const aLink = document.createElement('a');
  aLink.href = base64Data;
  aLink.download = filename;
  // 触发点击
  document.body.appendChild(aLink);
  aLink.click();
  // 清理无用的元素
  document.body.removeChild(aLink);
};

/** ERP 销售订单列表 */
defineOptions({name: 'ErpSaleOrder'})

const message = useMessage() // 消息弹窗
const {t} = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const dialogProductVisible = ref(false)

//修改备注
const dialogRemarkVisible = ref(false)
const updateRemarkData = reactive({
  id: undefined,
  remark: undefined
})

const showLeftData = ref(false)
const dialogCompleteDateVisible = ref(false)
const dialogInventoryVisible = ref(false)
const list = ref<SaleOrderVO[]>([]) // 列表的数据

const total = ref(0) // 列表的总页数

const prepareRadio = ref(1)
const completeRadio = ref(0)
const auditStatusRadio = ref(1)
const purchaseRadio = ref(0)

const payRadio = ref(0)
const getPayRadio = ref(0)

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  no: undefined,
  customerId: undefined,
  typeCar: undefined,
  completeStatus: undefined,
  prepareStatus: undefined,
  licensePlate: undefined,
  annotationTxt: undefined,
  productId: undefined,
  orderTime: [],
  completeDate: [],
  status: undefined,
  remark: undefined,
  creator: undefined,
  outStatus: undefined,
  returnStatus: undefined,
  productName:undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const productList = ref<ProductVO[]>([]) // 产品列表
const customerList = ref<CustomerVO[]>([]) // 客户列表
const userList = ref<UserVO[]>([]) // 用户列表
const syncProductInfoData = reactive({
  id: undefined,
  name: undefined,
  factoryNumber: undefined,
  oe: undefined,
  vin: undefined
})
const statusList = ref([

  {
    label: '未审批',
    value: 10
  },
  {
    label: '已审批',
    value: 20
  }
])
/**
 * 处理完工时间
 */
const completeDateData = reactive({
  id: undefined,
  completeDate: undefined
})

const sumSalePrice = ref(0);
const sumPurchasePrice = ref(0);
const sumEngineerCost = ref(0);
const sumOutsourceCost = ref(0);//外协
const sumOtherCost = ref(0);//其他费用
const sumSaleCost = ref(0);//销售员费用
const sumChannelCost = ref(0);//渠道费用

const getSummaries = (param) => {

  const {columns, data} = param
  const sums: string[] = []
  columns.forEach((column, index: number) => {

    if (['sumSalePrice'].includes(column.property)) {
      sums[index] = '' + erpPriceInputFormatter(sumSalePrice.value);
    } else if (['sumPurchasePrice'].includes(column.property)) {
      sums[index] = '' + erpPriceInputFormatter(sumPurchasePrice.value);
    } else if (['sumEngineerCost'].includes(column.property)) {
      sums[index] = '' + erpPriceInputFormatter(sumEngineerCost.value);
    } else if (['sumOutsourceCost'].includes(column.property)) {
      sums[index] = '' + erpPriceInputFormatter(sumOutsourceCost.value);
    } else if (['sumOtherCost'].includes(column.property)) {
      sums[index] = '' + erpPriceInputFormatter(sumOtherCost.value);
    } else if (['sumSaleCost'].includes(column.property)) {
      sums[index] = '' + erpPriceInputFormatter(sumSaleCost.value);
    } else if (['sumChannelCost'].includes(column.property)) {
      sums[index] = '' + erpPriceInputFormatter(sumChannelCost.value);
    } else if (['sumGrossProfit'].includes(column.property)) {
      let data = erpPriceInputFormatter(sumSalePrice.value) - erpPriceInputFormatter(sumPurchasePrice.value) - erpPriceInputFormatter(sumEngineerCost.value) - erpPriceInputFormatter(sumOutsourceCost.value) - erpPriceInputFormatter(sumOtherCost.value) - erpPriceInputFormatter(sumSaleCost.value) - erpPriceInputFormatter(sumChannelCost.value);
      sums[index] = '' + erpPriceInputFormatter(data);
    } else {
      sums[index] = ''
    }
  })

  return sums
}

const {push} = useRouter()
/**
 * 查看采购单
 * @param id
 */
const handleQueryPurchaseOrder = async (id: number) => {

  //查询中
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '查询中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    let data = await SaleOrderApi.queryPurchaseOrderById(id);
    push({
      path: "/erp/purchase/order",
      query: {doType: "query", data: data}
    });
  } finally {
    loadingInstance.close();
  }

}


/**
 * 查看采购入库单
 * @param id
 */
const handleQueryPurchaseIn = async (id: number) => {


  //查询中
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '查询中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    let data = await SaleOrderApi.queryPurchaseInById(id);
    push({
      path: "/erp/purchase/in",
      query: {doType: "query", data: data}
    });
  } finally {
    loadingInstance.close();
  }
}
/**
 * 查看付款单
 * @param id
 */
const handleQueryPay = async (id: number) => {
  //查询中
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '查询中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    let data = await SaleOrderApi.queryFinancePaymentById(id);
    push({
      path: "/erp/finance/payment",
      query: {doType: "query", data: data}
    });
  } finally {
    loadingInstance.close();
  }
}

/**
 * 查看收款
 * @param id
 */
const handleQueryReceipt = async (id: number) => {
  //查询中
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '查询中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    let data = await SaleOrderApi.queryFinanceReceiptById(id);
    push({
      path: "/erp/finance/receipt",
      query: {doType: "query", data: data}
    });
  } finally {
    loadingInstance.close();
  }
}

//关联查询销售出库单
const handleQuerySaleOut = async (id: number) => {
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '查询中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    let data = await SaleOrderApi.querySaleOutById(id);
    push({
      path: "/erp/sale/out",
      query: {doType: "query", data: data}
    });
  } finally {
    loadingInstance.close();
  }
}


const handleSyncPurchasePrice = async () => {

  //价格必须大于0
  if (purchaseInfo.value.some(item => item.purchasePrice < 0)) {
    ElMessage.error('采购价必须大于等于0')
    return
  }

  const loadingInstance = ElLoading.service({
    lock: true,
    text: '修改中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    await SaleOrderApi.syncPurchasePrice(purchaseInfo.value);
    ElMessage.success('修改成功');
  } finally {
    loadingInstance.close()
    dialogPurchaseVisible.value = false;
    getList();

  }

}


const dealCompleteDate = async () => {

  if (completeDateData.completeDate == undefined || completeDateData.completeDate == null) {
    ElMessage.error('请选择完工日期')
    return
  }
  completeDateData.completeDate = new Date(completeDateData.completeDate).getTime();
  // completeDateData.completeDate  = formatDate(completeDateData.completeDate);
  //时间不能大于今天
  if (completeDateData.completeDate > new Date().getTime()) {
    ElMessage.error('完工日期不能大于今天')
    return
  }
  loading.value = true
  try {
    await SaleOrderApi.updateCompleteDate(completeDateData)
    getList();
  } finally {
    dialogCompleteDateVisible.value = false;
    loading.value = false
    //提示修改成功
    ElMessage.success('修改成功')
  }
}
const handleCompleteDateClick = (row) => {
  completeDateData.id = row.id;
  completeDateData.completeDate = new Date();
  dialogCompleteDateVisible.value = true
}


const openPopoverVisible = async (id) => {
  popoverVisible.value = id;
}

const closePopover = async () => {
  popoverVisible.value = null;
}
const handleRightClick = (id) => {
  popoverVisible.value = id;
};

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await SaleOrderApi.getSaleOrderPage(queryParams)
    let page = data.page;
    list.value = page.list;
    total.value = page.total;

    let statistics = data.statistics;
    sumSalePrice.value = statistics.sumSalePrice;
    sumPurchasePrice.value = statistics.sumPurchasePrice;
    sumEngineerCost.value = statistics.sumEngineerCost;
    sumOutsourceCost.value = statistics.sumOutsourceCost;
    sumOtherCost.value = statistics.sumOtherCost;
    sumSaleCost.value = statistics.sumSaleCost;
    sumChannelCost.value = statistics.sumChannelCost;
  } finally {
    loading.value = false
  }
}


/**
 * 根据销售单生成采购单
 * @param id
 */
const handleCreatePurchaseOrder = async (id) => {
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在生成采购单',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  try {
    await SaleOrderApi.createPurchaseOrderBySaleOrder(id)
    ElMessage.success('生成采购单成功')
    getList();
  } finally {
    loadingInstance.close();
  }
}

/**
 * 修改采购价
 */
const dialogPurchaseVisible = ref(false);
const purchaseInfo = ref([]);
const handleUpdatePurchasePrice = async (row) => {
  //提示加载中
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '查询中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  try {
    let id = row.id;
    let data = await SaleOrderApi.getPurchaseBySaleOrderId(id);
    purchaseInfo.value = data;
    dialogPurchaseVisible.value = true;
  } finally {
    loadingInstance.close();
  }
}

/**
 * 修改技师提成
 * @param row
 */
const handleUpdateEngineerCost = async (row) => {
  dialogEngineerVisible.value = true;

  updateEngineerCostRow.value = row;

  let list = JSON.parse(JSON.stringify(row.engineerList));
  formEngineerData.value = list;
}
const updateEngineerCostRow = ref(null);
/**
 * 同步技师信息
 */
const handleSyncEngineerList = async () => {
  //校验 技师重复
  if (formEngineerData.value.some((item, index, array) => {
    return array.findIndex((item2, index2, array2) => {
      return item2.id == item.id && index2 != index;
    }) != -1;
  })) {
    ElMessage.error('技师重复添加')
    return
  }
  //校验金额大于0
  if (formEngineerData.value.some(item => item.cost < 0)) {
    ElMessage.error('技师提成必须大于等于0')
    return
  }
  //技师不能为空
  if (formEngineerData.value.some(item => item.id == null)) {
    ElMessage.error('请选择技师')
    return
  }

  const loadingInstance = ElLoading.service({
    lock: true,
    text: '修改中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  updateEngineerCostRow.value.engineerList = formEngineerData.value;
  try {
    await SaleOrderApi.syncEngineerList(updateEngineerCostRow.value);
    ElMessage.success('修改成功');
  } finally {
    dialogEngineerVisible.value = false;
    loadingInstance.close();
    getList();
  }
}

/** 完工状态搜索按钮操作 */
const handleCompleteQuery = (status) => {
  queryParams.completeStatus = status;
  getList()
}

const handleAuditStatusQuery = (status) => {
  queryParams.status = status;
  getList()
}
const handlePurchaseQuery = (status) => {
  queryParams.purchaseStatus = status;
  getList()
}

/** 备货状态搜索按钮操作 */
const handlePrepareQuery = (status) => {
  queryParams.prepareStatus = status;
  getList()
}

// 已付款
const handlePayQuery = (status) => {
  queryParams.payStatus = status;
  getList()
}
// 已收款
const handleGetPayQuery = (status) => {
  queryParams.receiptStatus = status;
  getList()
}


/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const computeAllPrice = (row) => {
  let items = row.items;
  if (items == undefined || items == null) {
    return 0;
  }
  let allPrice = 0;
  // 遍历所有项目
  for (let i = 0; i < items.length; i++) {
    let item = items[i];
    let price = item.productPrice;
    let count = item.count;
    allPrice = allPrice + price * count;
  }
  return allPrice;
}

//合计技师费用
function getEngineerCost(list) {
  let sum = 0;
  for (const listKey in list) {
    sum += list[listKey].cost;
  }
  return sum;
}

//产品成本价
const getPurchasePrice = (row) => {
  let items = row.items;

  if (items == undefined || items == null) {
    return 0;
  }

  let allPrice = 0;
  // 遍历所有项目
  for (let i = 0; i < items.length; i++) {
    let purchaseItem = items[i].purchaseOrderItems;
    if (purchaseItem == null) {
      break;
    }
    for (let j = 0; j < purchaseItem.length; j++) {
      let item = purchaseItem[j];
      allPrice = allPrice + (item.price * item.count);
    }
  }
  return allPrice;
}


const handleSyncProductInfo = async () => {

  if (syncProductInfoData.name === undefined && syncProductInfoData.factoryNumber === undefined) {
    ElMessage.error('请输入产品名称或工厂产品编号')
    return;
  }
  const loading = ElLoading.service({
    lock: true,
    text: '同步中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  try {
    await ProductApi.syncProductFactoryInfoById(syncProductInfoData);
  } finally {
    setTimeout(() => {
      loading.close()
    }, 500)
  }
  ElMessage({
    message: '同步成功',
    type: 'success',
  })
}

const handleProductClick = async (item) => {


  const loading = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  syncProductInfoData.id = item.productId;

  try {
    let product = await ProductApi.getProduct(item.productId);
    syncProductInfoData.name = product.name;
    syncProductInfoData.factoryNumber = product.factoryNumber;

    dialogProductVisible.value = true
  } finally {
    setTimeout(() => {
      loading.close()
    })
  }

}

//合计外协费用
function getOutsourceCost(list) {
  let sum = 0;
  for (const listKey in list) {
    sum += list[listKey].cost;
  }
  return sum;
}

//合计其他费用
function getOtherCost(list) {
  let sum = 0;
  for (const listKey in list) {
    sum += list[listKey].cost;
  }
  return sum;
}

const handleCompleteStatusChange = async (row) => {

  const completeStatusOptions = getIntDictOptions(DICT_TYPE.ERP_COMPLETE_STATUS);

  for (const key in completeStatusOptions) {
    if (completeStatusOptions[key].value === row.completeStatus) {

      await ElMessageBox.confirm(
        '【' + row.customerName + '】订单的完工状态是否修改为【' + completeStatusOptions[key].label + '】?',
        '完工状态确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(async () => {
          const loading = ElLoading.service({
            lock: true,
            text: '处理中...',
            background: 'rgba(0, 0, 0, 0.7)',
          })

          try {
            await SaleOrderApi.updateCompleteStatus(row.id, row.completeStatus);
            ElMessage({
              type: 'success',
              message: '完工状态已调整',
            })
          } finally {
            loading.close()
          }
        })
        .catch(() => {
        }).finally(() => {
          getList()
        })
    }
  }

}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.customerId = undefined;
  queryParams.prepareStatus = undefined;
  queryParams.completeStatus = undefined;
  queryParams.completeDate = [];
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {

  //加载中
  const loading = ElLoading.service({
    lock: true,
    text: '查询中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  try {
    formRef.value.open(type, id);
    popoverVisible.value = null;
  } finally {
    loading.close()
  }
}

/** 删除按钮操作 */
const handleDelete = async (ids: number[]) => {
  // 删除的二次确认
  await message.delConfirm()

  const loading = ElLoading.service({
    lock: true,
    text: '处理中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  try {

    // 发起删除
    await SaleOrderApi.deleteSaleOrder(ids)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
    selectionList.value = selectionList.value.filter((item) => !ids.includes(item.id))
  } catch {
  } finally {
    loading.close()
  }
}


const handleSendOrder = async (id: number) => {
  await message.confirm(`确定发单吗？`)

  printData.value = {};

  const loading = ElLoading.service({
    lock: true,
    text: '获取发单信息...',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  const getData = await SaleOrderApi.getInventory(id);
  printData.value = getData;

  dialogInventoryVisible.value = true;
  loading.close();
}

/** 审批/反审批操作 */
const handleUpdateStatus = async (id: number, status: number) => {

  // 审批的二次确认
  await message.confirm(`确定${status === 20 ? '审批' : '反审批'}该订单吗？`)
  const loading = ElLoading.service({
    lock: true,
    text: '处理中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  try {
    // 发起审批
    try {
      await SaleOrderApi.updateSaleOrderStatus(id, status);
    } finally {

    }


    // if (status === 20) {
    //   let saleOrder = await SaleOrderApi.getSaleOrder(id);
    //
    //   //自动销售出库
    //   const saleOutForm = {
    //     customerId: saleOrder.customerId,
    //     accountId: 4,
    //     saleUserId: undefined,
    //     outTime: Date.now(),
    //     remark: undefined,
    //     fileUrl: '',
    //     discountPercent: 0,
    //     discountPrice: 0,
    //     totalPrice: saleOrder.totalProductPrice,
    //     otherPrice: 0,
    //     orderId: saleOrder.id,
    //     orderNo: saleOrder.no,
    //     items: [],
    //     no: undefined // 出库单号，后端返回
    //   }
    //
    //   saleOrder.items.forEach(item => {
    //     saleOutForm.items.push({
    //       productId: item.productId,
    //       supplierId: null,
    //       purchasePrice: null,
    //       productUnitId: item.productUnitId,
    //       productPrice: item.productPrice,
    //       count: item.count,
    //       taxPercent: null,
    //       taxPrice: 0,
    //       remark: null,
    //       outCount: 0,
    //       returnCount: 0,
    //       productName: item.productName,
    //       productBarCode: item.productBarCode,
    //       productUnitName: item.productUnitName,
    //       stockCount: item.stockCount,
    //       orderItemId: item.id,
    //       warehouseId: 3
    //     })
    //   })
    //
    //   let outId = await SaleOutApi.createSaleOut(saleOutForm);
    //   //自动销售出库审批
    //   await SaleOutApi.updateSaleOutStatus(outId, 20);
    // }
    message.success(`${status === 20 ? '审批' : '反审批'}成功`)
    // 刷新列表
    await getList()
  } catch {
  } finally {
    loading.close()
  }
}


const getGrossProfit = (row) => {
  //销售价
  let allPrice = computeAllPrice(row);

  //其他费用
  let otherCost = getOtherCost(row.otherCostList);

  //技师费用
  let engineerCost = getEngineerCost(row.engineerList);

  //采购价
  let purchasePrice = getPurchasePrice(row);

  //外协费用
  let outsourceCost = getOutsourceCost(row.outsourceList);

  return allPrice - otherCost - engineerCost - outsourceCost - row.saleUserCost - row.channelCost - purchasePrice;
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await SaleOrderApi.exportSaleOrder(queryParams)
    download.excel(data, '销售订单.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 选中操作 */
const selectionList = ref<SaleOrderVO[]>([])
const handleSelectionChange = (rows: SaleOrderVO[]) => {
  selectionList.value = rows
}


const dialogEngineerVisible = ref(false);
/** 新增按钮操作 */
const handleEngineerAdd = () => {
  const engineerRow = {
    id: undefined,
    name: undefined,
    cost: 0,
    remark: undefined
  }
  if (formEngineerData.value == null) {
    formEngineerData.value = []
  }
  formEngineerData.value.push(engineerRow)
}
const handleEngineerDelete = (index: number) => {
  formEngineerData.value.splice(index, 1)
}
if (onMounted) {
  /** 初始化 **/
  onMounted(async () => {

    await getList()
    // 加载产品、仓库列表、客户
    productList.value = await ProductApi.getProductSimpleList()
    customerList.value = await CustomerApi.getCustomerSimpleList()
    userList.value = await UserApi.getSimpleUserList()

    /**
     * 获取技师
     */
    const data = await EngineerApi.simpleList();
    engineerList.value = data;
    if (formEngineerData.value.length === 0) {
      handleEngineerAdd()
    }
  })
}

if (onActivated) {
  onActivated(() => {
    popoverVisible.value = null;
    getList()
  });
}
// TODO eGlass：可优化功能：列表界面，支持导入
// TODO eGlass：可优化功能：详情界面，支持打印

/** 用户导入 */
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}

</script>


<style scoped>
.custom-select .el-input__inner {
  /* 默认颜色 */
  color: #303133;
}

.priorit1 .el-input__inner {
  color: red; /* taskLevel 为 2 时的颜色 */
}

.priorit2 .el-input__inner {
  color: blue; /* taskLevel 为 3 时的颜色 */
}
</style>
<style lang="scss" scoped>
.is-link {
  margin: 0px;
}

.el-dialog__title {
  font-size: 20px;
}


.el-form--inline .el-form-item {
    margin-right: 20px;
}
</style>
